﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinformToolkit.Drawing
{
    public partial class PreviewArea : UserControl
    {
        #region 类变量

        private static readonly Brush BackgroundBrush = new SolidBrush(Color.FromArgb(200, Color.Black));
        private static readonly Brush ViewportAreaBrush = new SolidBrush(Color.FromArgb(0, Color.White));

        #endregion

        #region 实例变量

        /// <summary>
        /// 预览图像的显示区域
        /// </summary>
        private Rectangle previewImageArea;

        #endregion

        #region 属性

        /// <summary>
        /// 要显示的预览图像
        /// </summary>
        internal Image PreviewImage { get; set; }

        /// <summary>
        /// 基于整个图像的视野位置
        /// 单位是百分比，而不是像素
        /// </summary>
        internal RectangleF ViewportArea { get; set; }

        #endregion

        #region 构造方法

        public PreviewArea()
        {
            InitializeComponent();

            this.InitializeUserControl();
        }

        #endregion

        #region 实例方法

        private void InitializeUserControl()
        {
        }

        #endregion

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            this.PerformPaint(e);
        }

        internal void PerformPaint(PaintEventArgs pevent)
        {
            Graphics g = pevent.Graphics;

            Rectangle rectangle = pevent.ClipRectangle;
            rectangle.Width -= 1;
            rectangle.Height -= 1;

            g.DrawRectangle(Pens.Black, rectangle);

            // 画边框
            if (this.PreviewImage != null)
            {
                g.DrawImage(this.PreviewImage, Point.Empty);

                // 根据比例计算要显示的视野大小
                float x = this.previewImageArea.X + this.previewImageArea.Width * this.ViewportArea.X;
                float y = this.previewImageArea.Y + this.previewImageArea.Height * this.ViewportArea.Y;
                float width = this.previewImageArea.Width * this.ViewportArea.Width;
                float height = this.previewImageArea.Height * this.ViewportArea.Height;

                // 先画一个黑透明的背景
                g.FillRectangle(BackgroundBrush, this.ClientRectangle);

                // 再把ViewportArea画成白色全透明的
                g.FillRectangle(ViewportAreaBrush, x, y, width, height);

                // 再把ViewportArea画个白色边框
                g.DrawRectangle(Pens.White, x, y, width, height);
            }
        }
    }
}
